import React, { useEffect, useState } from 'react';
import { Button, App, Modal, Input } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { DragDropContext, Droppable, Draggable, DropResult } from 'react-beautiful-dnd';
import FusionAppItem from './FusionAppItem';
import BoxInfo from '@/components/box/boxInfo';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { GetWorkBenhList } from '@/common';
import Modals from '@/components/modals/Modals';
import { SvgIcon } from '@/components/icon';
import '@/components/work-modal/work.scss';

interface AppItem {
  id: string;
  name: string;
  description: string;
  icon?: React.ReactNode;
}

const FusionAppSettings: React.FC = () => {
  const [apps, setApps] = useState<AppItem[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedApps, setSelectedApps] = useState<GetWorkBenhList[]>([]);
  const [searchText, setSearchText] = useState<string>('');
  const { appDetail, setAppDetail, configurations, appName, appDescription, appLogo } =
    useOrchestrationStore();
  const { message } = App.useApp();
  useEffect(() => {
    console.log('apps', apps);
  }, [apps]);

  useEffect(() => {
    const fusionApps = appDetail?.fusionApp || [];
    setApps(
      fusionApps.map((app: any) => ({
        id: app.appId,
        name: app.name,
        description: app.intro,
        icon: app?.appLogo || app?.icon,
      })),
    );
  }, [appDetail]);

  const onDragEnd = (result: DropResult) => {
    if (!result.destination) return;
    const newApps = Array.from(apps);
    const [removed] = newApps.splice(result.source.index, 1);
    newApps.splice(result.destination.index, 0, removed);
    setApps(newApps);
    setTimeout(() => {
      setAppDetail({
        ...appDetail,
        configurations: configurations,
        app_name:
          configurations.find((config) => config.name === 'app_name')?.default_value || appName,
        app_description:
          configurations.find((config) => config.name === 'app_description')?.default_value ||
          appDescription ||
          '',
        app_logo:
          configurations.find((config) => config.name === 'app_logo')?.default_value || appLogo,
        fusionApp: newApps.map((app) => ({
          appId: app.id,
          name: app.name,
          intro: app.description,
          icon: app.icon,
        })),
      });
    }, 500);
  };

  const handleAdd = () => {
    setIsModalVisible(true);
    setSelectedApps([]);
    setSearchText('');
  };

  const handleModalOk = () => {
    const fusionApps = appDetail?.fusionApp || [];
    const fusionAppList = fusionApps.map((app: any) => ({
      id: app.appId,
      name: app.name,
      description: app.intro,
      icon: app?.appLogo || app?.icon,
    }));

    const selectedAppList = selectedApps.map((app: any) => ({
      id: app.app_id,
      name: app.app_name,
      description: app.app_description,
      icon: app.app_logo,
    }));

    const newApps = [...fusionAppList, ...selectedAppList];

    const uniqueApps = newApps.filter(
      (app, index, self) => index === self.findIndex((a) => a.id === app.id),
    );

    setAppDetail({
      ...appDetail,
      configurations: configurations,
      app_name:
        configurations.find((config) => config.name === 'app_name')?.default_value || appName,
      app_description:
        configurations.find((config) => config.name === 'app_description')?.default_value ||
        appDescription ||
        '',
      app_logo:
        configurations.find((config) => config.name === 'app_logo')?.default_value || appLogo,
      fusionApp: uniqueApps.map((app) => ({
        appId: app.id,
        name: app.name,
        intro: app.description,
        icon: app.icon,
      })),
    });
    setIsModalVisible(false);
    setSelectedApps([]);
    // message.success(`成功添加 ${newApps.length} 个融合应用`);
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    setSelectedApps([]);
    setSearchText('');
  };

  const handleAppSelection = (selectedAppList: GetWorkBenhList[]) => {
    console.log(selectedAppList);

    setSelectedApps(selectedAppList);
  };

  const handleDelete = (id: string) => {
    setAppDetail({
      ...appDetail,
      configurations: configurations,
      app_name:
        configurations.find((config) => config.name === 'app_name')?.default_value || appName,
      app_description:
        configurations.find((config) => config.name === 'app_description')?.default_value ||
        appDescription ||
        '',
      app_logo:
        configurations.find((config) => config.name === 'app_logo')?.default_value || appLogo,
      fusionApp: apps
        .filter((app) => app.id !== id)
        .map((app) => ({
          appId: app.id,
          name: app.name,
          intro: app.description,
          icon: app.icon,
        })),
    });
    message.success('删除成功');
  };

  return (
    <div className="mx-auto h-full w-full rounded-md border-none bg-white p-0">
      <div className="mb-4 flex items-center">
        <span className="mr-2 h-4 w-1.5 rounded-full bg-blue-500" />
        <span className="text-lg font-semibold">融合应用</span>
      </div>
      <div className="mb-4 text-xs text-gray-400">
        选择需要融合的应用，在对话页面可输入@并选择对应应用即可使用，排序在前的应用会优先展示。未选择应用则使用大模型进行闲聊。
      </div>
      <Button
        type="text"
        icon={<PlusOutlined />}
        block
        className="!border-1 mb-4 !h-10 !rounded-md !border !border-primary"
        onClick={handleAdd}
      >
        添加融合应用
      </Button>
      <div className="max-h-[calc(100vh-400px)] overflow-auto [-ms-overflow-style:none] [scrollbar-width:none]">
        <DragDropContext onDragEnd={onDragEnd}>
          <Droppable droppableId="fusion-apps">
            {(provided) => (
              <div ref={provided.innerRef} {...provided.droppableProps}>
                {apps.map((app, index) => (
                  <Draggable key={app.id} draggableId={app.id} index={index}>
                    {(provided, snapshot) => (
                      <div
                        key={app.id}
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        className="board-none rounded-md"
                        style={{
                          ...provided.draggableProps.style,
                          boxShadow: snapshot.isDragging
                            ? '0 4px 12px rgba(0,0,0,0.08)'
                            : undefined,
                        }}
                      >
                        <FusionAppItem
                          name={app.name}
                          description={app.description}
                          icon={app.icon}
                          onDelete={() => handleDelete(app.id)}
                          dragHandleProps={provided.dragHandleProps || {}}
                        />
                      </div>
                    )}
                  </Draggable>
                ))}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </DragDropContext>
      </div>

      {/* 添加融合应用弹窗 */}
      <Modals
        destroyOnHidden
        title="选择融合应用"
        open={isModalVisible}
        onOk={handleModalOk}
        width={1000}
        onCancel={handleModalCancel}
        okText={`添加${Math.max(selectedApps.length, 0)}个应用`}
        cancelText="取消"
        // okButtonProps={{
        //   disabled: (Math.max(selectedApps.length - apps?.length, 0)) === 0,
        // }}
        footerOkDisabled={Math.max(selectedApps.length, 0) === 0}
        className="modals-mode"
      >
        <div className="flex justify-end">
          {/* <Input
            placeholder="搜索应用名称或描述"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            allowClear
            size="large"
          /> */}
          <Input
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            className="mb-[15px] !rounded-md"
            style={{
              height: '32px',
              width: '200px',
            }}
            placeholder="请输入内容"
            suffix={<SvgIcon icon="work-ic6" size={16} />}
          />
        </div>
        <BoxInfo
          searchText={searchText}
          isMultiSelect={2}
          paramsType="public"
          appType="agent,workflow"
          confirm={handleAppSelection}
          selectApps={apps}
        />
      </Modals>
    </div>
  );
};

export default FusionAppSettings;
